package com.mti.epivisitemobile.model
{
	import com.mti.epivisite.common.Configuration;
	import com.mti.epivisite.common.event.EpivisiteEvent;
	
	import mx.collections.ArrayCollection;
	import mx.messaging.Channel;
	import mx.messaging.ChannelSet;
	import mx.messaging.channels.AMFChannel;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.RemoteObject;
	
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	public class EventListProxy extends EventListProxyBase
	{
		public function EventListProxy()
		{
			super();
			
			var channelSet:ChannelSet = new ChannelSet();
			var channel:Channel = new AMFChannel("my-amf", Configuration.SERVER_CHANNEL_URI);
			channelSet.addChannel(channel);
			
			_remoteObject = new RemoteObject("interface");
			_remoteObject.source = "com.serverplic.media.MediaInterface";
			_remoteObject.channelSet = channelSet;
		}
		
		private var _remoteObject:RemoteObject = null;
		
		private var _events:ArrayCollection = null;
		public override function get events():ArrayCollection
		{
			return _events;
		}
		
		public override function getEventList():void
		{
			_remoteObject.getEventList.addEventListener(ResultEvent.RESULT, onGetEventListResult);
			_remoteObject.getEventList.addEventListener(FaultEvent.FAULT, onGetEventListFault);
			
			_remoteObject.getEventList();
		}
		
		private function onGetEventListResult(event:ResultEvent):void
		{
			_remoteObject.getEvent.removeEventListener(ResultEvent.RESULT, onGetEventListResult);
			_remoteObject.getEvent.removeEventListener(FaultEvent.FAULT, onGetEventListFault);
			
			var resultCollection:ArrayCollection = event.result as ArrayCollection;
			_events = new ArrayCollection();
			for each (var o:Object in resultCollection)
			{
				var eventObject:EpivisiteEvent = new EpivisiteEvent();
				eventObject.name = o["name"];
				eventObject.id = o["id"];
				eventObject.password = o["password"];
				eventObject.description = o["description"];
				eventObject.startDate = o["startDate"];
				eventObject.endDate = o["endDate"];
				
				_events.addItem(eventObject);
			}
			
			sendNotification(LOAD_SUCCESS);
		}
		
		private function onGetEventListFault(event:FaultEvent):void
		{
			_remoteObject.getEvent.removeEventListener(ResultEvent.RESULT, onGetEventListResult);
			_remoteObject.getEvent.removeEventListener(FaultEvent.FAULT, onGetEventListFault);
			
			sendNotification(LOAD_ERROR);
		}
	}
}